/*
 * action 类型
 */
import api from '@/framework/axios';//请求接口的封装

export const type = {
  SWITCH_MENU: 'SWITCH_MENU',
  SET_TOKEN: 'SET_TOKEN',
  SET_AUTH: 'SET_AUTH'
}

// 菜单点击切换，修改面包屑名称
export function switchMenu(menuPath) {
  return {
    type: type.SWITCH_MENU,
    menuPath
  }
}


// 菜单点击切换，修改面包屑名称
export function setToken(token) {
  return {
    type: type.SET_TOKEN,
    token
  }
}


// 设置权限与菜单
function setAuth(data) {
  let authMenuList = data.authMenuList;
  let menuList = data.menuList;
  return {
    type: type.SET_AUTH,
    authMenuList,
    menuList,
  }
}


export function setUserAuth() {
  //从服务器异步获取
  return (dispatch, getState) => {
    api.ajax('GET', '@/auth/menuList').then(r => {
      let authMenuList = [];
      // 将菜单数据扁平化为一级
      function flatNavList(arr) {
        arr.map((v) => {
          if (v.children && v.children.length) {
            authMenuList.push(v);
            flatNavList(v.children);
          } else {
            authMenuList.push(v);
          }
        });
      }
      flatNavList(r.menuList);

      dispatch(setAuth({
        authMenuList,
        menuList: r.menuList
      }));
    })
  }
}